package com.yunti.yntk.activity.main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.yunti.yntk.R;
import com.yunti.yntk.activity.BaseActivity;
import com.yunti.yntk.activity.batchRecord.BatchRecordActivity;
import com.yunti.yntk.activity.record.RecordActivity;
import com.yunti.yntk.activity.stepper.StepperActivity_ty;
import com.yunti.yntk.activity.stepper.StepperActivity_tz;
import com.yunti.yntk.anotation.ViewInject;
import com.yunti.yntk.api.Result;
import com.yunti.yntk.db.AppDatabase;
import com.yunti.yntk.db.ExamItemDao;
import com.yunti.yntk.db.po.ExamItem;
import com.yunti.yntk.manager.ComputScoreManager;
import com.yunti.yntk.manager.NetWorkManager;

import com.yunti.yntk.service.ConnectService;
import com.yunti.yntk.util.CacheUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MainActivity extends BaseActivity {

    @ViewInject(R.id.gotoSportButton_ty)
    private TextView gotoSportButton_ty;

    @ViewInject(R.id.gotoSportButton_qq)
    private TextView gotoSportButton_qq;


    @ViewInject(R.id.gotoSportButton_tyzx)
    private TextView gotoSportButton_tyzx;

    @ViewInject(R.id.gotoSportButton_tzzx)
    private TextView gotoSportButton_tzzx;

    @ViewInject(R.id.gotoWebViewButton)
    private TextView gotoWebViewButton;

    @ViewInject(R.id.timeText)
    private TextView timeText;


    @ViewInject(R.id.cancel_button)
    private TextView cancel_button;

    @ViewInject(R.id.confirm_button)
    private TextView confirm_button;


    private ExamItemDao examItemDao;

    private ExamItemAdapter boyExamItemAdapter;
    List<ExamItem> boyExamItemList = new ArrayList<>();

    private ExamItemAdapter girlExamItemAdapter;
    List<ExamItem> girlExamItemList = new ArrayList<>();

    List<ExamItem> checkedExamItemList = new ArrayList<>();


    @Override
    public int initLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        Intent startIntent = new Intent(this, ConnectService.class);
        startService(startIntent);
        gotoSportButton_ty.setOnClickListener(this::gotoSport);
        gotoSportButton_qq.setOnClickListener(this::gotoSport);
        gotoSportButton_tyzx.setOnClickListener(this::gotoSport);
        gotoSportButton_tzzx.setOnClickListener(this::gotoSport);
        gotoWebViewButton.setOnClickListener(this::gotoRecord);

        boyExamItemAdapter = new ExamItemAdapter(this, R.layout.item_examitem, boyExamItemList);

        girlExamItemAdapter = new ExamItemAdapter(this, R.layout.item_examitem, girlExamItemList);

//        cancel_button.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                girlExamItemList.clear();
//                boyExamItemList.clear();
//                boyExamItemAdapter.notifyDataSetChanged();
//                girlExamItemAdapter.notifyDataSetChanged();
//                checkedExamItemList.clear();
//                CacheUtils.examItemList.clear();
//            }
//        });
//
//        confirm_button.setOnClickListener(this::confirmSport);


    }

    private void gotoRecord(View view) {
        Intent intent = new Intent(MainActivity.this, RecordActivity.class);
        startActivity(intent);
    }


    @Override
    public void initData() throws IOException {
        examItemDao = AppDatabase.getDatabase(getBaseContext()).examItemDao();
        StartTimeThread();
//        QMUITipDialog tipDialog = new QMUITipDialog.Builder(this)
//                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
//                .setTipWord("同步项目中...")
//                .create();
//        runOnUiThread(() -> {
//
//            tipDialog.show();
//        });
//
//        Call<Result<List<ExamItem>>> call = NetWorkManager.getRequest().getExamItemList();
//        call.enqueue(new Callback<Result<List<ExamItem>>>() {
//            @Override
//            public void onResponse(Call<Result<List<ExamItem>>> call, Response<Result<List<ExamItem>>> response) {
//                Result<List<ExamItem>> result = response.body();
//                if (result != null && result.getCode() == 200) {
//                    List<ExamItem> examItemList = result.getData();
//                    new Thread(() -> {
//                        examItemDao.deleteAll();
//                        examItemDao.insertAll(examItemList);
//                    }).start();
//                    Toast.makeText(getBaseContext(), "同步成功！", Toast.LENGTH_LONG).show();
//                }
//                runOnUiThread(() -> {
//
//                    tipDialog.dismiss();
//                });
//            }
//
//            @Override
//            public void onFailure(Call<Result<List<ExamItem>>> call, Throwable t) {
//                runOnUiThread(() -> {
//
//                    tipDialog.dismiss();
//                });
//            }
//        });
    }


    class ExamItemAdapter extends ArrayAdapter<ExamItem> {
        public ExamItemAdapter(@NonNull Context context, int resource, @NonNull List<ExamItem> objects) {
            super(context, resource, objects);
        }


        //每个子项被滚动到屏幕内的时候会被调用
        @SuppressLint("SetTextI18n")
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            ExamItem examItem = getItem(position);//得到当前项的 Fruit 实例
            //为每一个子项加载设定的布局
            @SuppressLint("ViewHolder")
            View view = LayoutInflater.from(getContext()).inflate(R.layout.item_examitem, parent, false);
            //分别获取 image view 和 textview 的实例
            TextView textView = view.findViewById(R.id.itemName);
            textView.setText(examItem.getXmmc());
            CheckBox checkBox = view.findViewById(R.id.checkbox);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (checkBox.isChecked()) {
                        checkBox.setChecked(false);
                        checkedExamItemList.remove(examItem);
                    } else {
                        checkBox.setChecked(true);
                        checkedExamItemList.add(examItem);
                    }
                    if (!examItem.getZxdm().equals("0027")) {
                        if (examItem.getXbdm().equals("1")) {
                            List delList = new ArrayList();
                            for (ExamItem e : checkedExamItemList) {
                                if (e.getXbdm().equals("2")) {
                                    delList.add(e);
                                }
                            }
                            checkedExamItemList.removeAll(delList);
                            girlExamItemAdapter.notifyDataSetChanged();
                        }
                        if (examItem.getXbdm().equals("2")) {
                            List delList = new ArrayList();
                            for (ExamItem e : checkedExamItemList) {
                                if (e.getXbdm().equals("1")) {
                                    delList.add(e);
                                }
                            }
                            checkedExamItemList.removeAll(delList);
                            boyExamItemAdapter.notifyDataSetChanged();
                        }
                    }
                    CacheUtils.examItemList = checkedExamItemList;
                    System.out.println(checkedExamItemList);
                }
            });
            return view;
        }
    }


    private Future timeFuture;
    private ExecutorService es = Executors.newSingleThreadExecutor();

    private void StartTimeThread() {
        timeFuture = es.submit(() -> {
            do {
                try {
                    Thread.sleep(1000);
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        });
    }

    Bitmap overlay;
    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    long time = System.currentTimeMillis();
                    CharSequence timeFormat = DateFormat.format("HH:mm:ss", time);
                    timeText.setText(timeFormat);
                    break;
            }
        }
    };

    private void gotoSport(View view) {
        int id = view.getId();
        boolean isInit = ComputScoreManager.getInstance().isInit();
        switch (id) {
            case R.id.gotoSportButton_ty:
                gotoTySz();
                break;
            case R.id.gotoSportButton_qq:
                gotoTzsz();
                break;
            case R.id.gotoSportButton_tyzx:
                gotoTyZx();
                break;
            case R.id.gotoSportButton_tzzx:
                gotoTzzx();
                break;
        }
    }

    public void gotoTySz() {
        Intent intent = new Intent(MainActivity.this, BatchRecordActivity.class);
        intent.putExtra("subId", 2);
        intent.putExtra("subName", "立定跳远");
        intent.putExtra("type", 1);
        startActivity(intent);

    }

    public void gotoTzsz() {
        boolean isInit = ComputScoreManager.getInstance().isInit();
        if (isInit) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("确认");
            builder.setMessage("检测到已初始化过，是否重新初始化全站仪？");
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent = new Intent(MainActivity.this, StepperActivity_tz.class);
                    intent.putExtra("subId", 3);
                    intent.putExtra("subName", "原地推铅球");
                    intent.putExtra("type", 1);
                    startActivity(intent);
                }
            });
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent intent = new Intent(MainActivity.this, BatchRecordActivity.class);
                    intent.putExtra("subId", 3);
                    intent.putExtra("subName", "原地推铅球");
                    intent.putExtra("type", 1);
                    startActivity(intent);
                }
            });
            builder.show();
        } else {
            Intent intent = new Intent(MainActivity.this, StepperActivity_tz.class);
            intent.putExtra("subId", 3);
            intent.putExtra("subName", "原地推铅球");
            intent.putExtra("type", 1);
            startActivity(intent);
        }
    }

    public void gotoTzzx() {
        boolean isInit = ComputScoreManager.getInstance().isInit();
        final String[] items2 = new String[]{"铅球", "铁饼", "标枪"};
        final Integer[] idList2 = new Integer[]{13, 14, 15};
        final QMUIDialog.CheckableDialogBuilder builder2 = new QMUIDialog.CheckableDialogBuilder(MainActivity.this);
        builder2.setTitle("请选择")
                .setCheckedIndex(0)
                .addItems(items2, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        builder2.setCheckedIndex(which);
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        Toast.makeText(MainActivity.this, "你选择了 " + items2[builder2.getCheckedIndex()], Toast.LENGTH_SHORT).show();
                        dialog.dismiss();

                        if (isInit) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setTitle("确认");
                            builder.setMessage("检测到已初始化过，是否重新初始化全站仪？");
                            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Intent intent = new Intent(MainActivity.this, StepperActivity_tz.class);
                                    intent.putExtra("subId", idList2[builder2.getCheckedIndex()]);
                                    intent.putExtra("subName", items2[builder2.getCheckedIndex()]);
                                    intent.putExtra("type", 2);
                                    startActivity(intent);
                                }
                            });
                            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Intent intent = new Intent(MainActivity.this, BatchRecordActivity.class);
                                    intent.putExtra("subId", idList2[builder2.getCheckedIndex()]);
                                    intent.putExtra("subName", items2[builder2.getCheckedIndex()]);
                                    intent.putExtra("type", 2);
                                    startActivity(intent);
                                }
                            });
                            builder.show();
                        } else {
                            Intent intent = new Intent(MainActivity.this, StepperActivity_tz.class);
                            intent.putExtra("subId", idList2[builder2.getCheckedIndex()]);
                            intent.putExtra("subName", items2[builder2.getCheckedIndex()]);
                            intent.putExtra("type", 2);
                            startActivity(intent);
                        }

                    }
                })
                .show();
    }

    public void gotoTyZx() {
        boolean isInit = ComputScoreManager.getInstance().isInit();
        final String[] items = new String[]{"跳远", "三级跳远", "立定三级跳远"};
        final Integer[] idList = new Integer[]{11, 12,13};
        final QMUIDialog.CheckableDialogBuilder checkableDialogBuilder = new QMUIDialog.CheckableDialogBuilder(MainActivity.this);
        checkableDialogBuilder.setTitle("请选择")
                .setCheckedIndex(0)
                .addItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        checkableDialogBuilder.setCheckedIndex(which);
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        Toast.makeText(MainActivity.this, "你选择了 " + items[checkableDialogBuilder.getCheckedIndex()], Toast.LENGTH_SHORT).show();
                        dialog.dismiss();

                        if (isInit) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setTitle("确认");
                            builder.setMessage("检测到已初始化过，是否重新初始化全站仪？");
                            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                    if(idList[checkableDialogBuilder.getCheckedIndex()]==13){
                                        Intent intent = new Intent(MainActivity.this, StepperActivity_ty.class);
                                        intent.putExtra("subId", 2);
                                        intent.putExtra("subName", "立定三级跳远");
                                        intent.putExtra("type", 1);
                                        startActivity(intent);
                                    } else{
                                        Intent intent = new Intent(MainActivity.this, StepperActivity_ty.class);
                                        intent.putExtra("subId", idList[checkableDialogBuilder.getCheckedIndex()]);
                                        intent.putExtra("subName", items[checkableDialogBuilder.getCheckedIndex()]);
                                        intent.putExtra("type", 2);
                                        startActivity(intent);
                                    }
                                }
                            });
                            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {


                                    if(idList[checkableDialogBuilder.getCheckedIndex()]==13){
                                        Intent intent = new Intent(MainActivity.this, BatchRecordActivity.class);
                                        intent.putExtra("subId", 2);
                                        intent.putExtra("subName","立定三级跳远");
                                        intent.putExtra("type", 1);
                                        startActivity(intent);
                                    } else{
                                        Intent intent = new Intent(MainActivity.this, BatchRecordActivity.class);
                                        intent.putExtra("subId", idList[checkableDialogBuilder.getCheckedIndex()]);
                                        intent.putExtra("subName", items[checkableDialogBuilder.getCheckedIndex()]);
                                        intent.putExtra("type", 2);
                                        startActivity(intent);
                                    }
                                }
                            });
                            builder.show();
                        } else {
                            Intent intent = new Intent(MainActivity.this, StepperActivity_ty.class);
                            intent.putExtra("subId", idList[checkableDialogBuilder.getCheckedIndex()]);
                            intent.putExtra("subName", items[checkableDialogBuilder.getCheckedIndex()]);
                            intent.putExtra("type", 2);
                            startActivity(intent);
                        }
                    }
                })
                .show();
    }
}
